<?php namespace Phpcmf\Admin;

/**
 * https://duixin.cc
 * 本文件是框架系统文件，二次开发时不可以修改本文件，可以通过继承类方法来重写此文件
 **/

// 评论操作类 基于 Ftable
class Mform extends \Phpcmf\Table
{
    public $cid; // 内容id
    public $module; // 模块信息
    public $form; // 表单
    public $module_menu; // 是否显示模块菜单
    public $is_verify; // 来自审核
    public $comment_model; // 评论模型
    protected $cname; // 评论别名

    // 上级公共类
    public function __construct() {
        parent::__construct();
        $this->_Extend_Init();
    }


    public function _get_auth_value($name, $member) {

        if (!$this->module['comment'][$name]) {
            return 0;
        }

        if (!$member) {
            $auth = [0];
        } else {
            $auth = $member['groupid'];
            if (!$auth) {
                return 0;
            }
        }

        $value = [];
        foreach ($auth as $k) {
            if (isset($this->module['comment'][$name][$k])) {
                $value[] = (int)$this->module['comment'][$name][$k];
            }
        }

        return max($value);
    }

    // 继承类初始化
    protected function _Extend_Init() {
        // 初始化模块
        $this->_module_init(APP_DIR);
        $fid = str_replace(['_comment_verify', '_comment'], '', \Phpcmf\Service::L('Router')->class);
        if (!$this->module['form'][$fid]) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】不存在', APP_DIR, $fid));
        }
        $this->module['comment'] = $cache = \Phpcmf\Service::L('cache')->get('app-comment-'.SITE_ID, 'mform', APP_DIR.'-'.$fid);
        $this->form = $this->module['form'][$fid];
        $this->cname = $this->module['comment']['name'] = dr_comment_cname($cache['cname']);
        if (!$cache) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】没有安装%s', APP_DIR, $fid, $this->cname));
        } elseif (!$cache['use']) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】没有启用%s', APP_DIR, $fid, $this->cname));
        }
        $this->comment_model = \Phpcmf\Service::M('mform', 'comment')->_init($this->module, $fid, SITE_ID, $cache);
        // 指定后台模板路径
        $this->admin_tpl_path = dr_get_app_dir('comment').'Views/';
        // 支持附表存储
        $this->is_data = 0;
        // 模板前缀(避免混淆)
        $this->tpl_prefix = 'share_comment_';
        // 单独模板命名
        $this->tpl_name = 'comment_'.$fid;
        // 模块显示名称
        $this->name = dr_lang('内容模块[%s]表单[%s]%s', APP_DIR, $fid, $this->cname);
        // 获取父级内容
        $this->cid = intval(\Phpcmf\Service::L('input')->get('cid'));
        $this->cid && $this->index = $this->comment_model->get_row( $this->cid);
        // 自定义字段
        if (!$this->module['comment']['comment_list_field']) {
            $this->module['comment']['comment_list_field'] = [
                'content' => [
                    'use' => 1,
                    'name' => dr_lang('内容'),
                    'func' => 'comment',
                    'width' => 0,
                ],
            ];
        }
        $this->module['comment']['field'] = dr_array22array(
            [
                'content' => [
                    'name' => dr_lang('内容'),
                    'ismain' => 1,
                    'fieldtype' => 'Ueditor',
                    'fieldname' => 'content',
                    'setting' => array(
                        'option' => array(
                            'height' => 250,
                            'mode' => 1,
                            'width' => '100%'
                        )
                    ),
                ]
            ],
            $this->module['comment']['field']
        );
        $this->module['comment']['field']['author'] = [
            'name' => dr_lang('作者'),
            'ismain' => 1,
            'fieldtype' => 'Text',
            'fieldname' => 'author',
            'setting' => array(
                'is_right' => 1,
                'option' => array(
                    'width' => '200'
                )
            ),
        ];
        // 判断是否来自审核控制器
        $this->is_verify = strpos(\Phpcmf\Service::L('Router')->class, '_verify') !== false;
        // 自定义条件
        $where = $this->is_verify ? 'status<>1' : 'status=1';
        $this->cid && $where.= ' and cid='. $this->cid;
        $sysfield = ['inputtime', 'inputip', 'uid'];

        if ($this->is_verify) {
            $sysfield[] = 'status';
            if (is_array($this->module['comment']['comment_list_field'])) {
                $this->module['comment']['comment_list_field']['status'] = [
                    'use' => '1', // 1是显示，0是不显示
                    'name' => dr_lang('状态'), //显示名称
                    'width' => '100', // 显示宽度
                    'func' => 'dr_comment_status_name', // 回调函数见：https://duixin.cc/help/463.html
                    'center' => '1', // 1是居中，0是默认
                ];
            }
        }

        // 初始化数据表
        $this->_init([
            'table' => dr_module_table_prefix(APP_DIR).'_form_'.$fid.'_comment',
            'field' => $this->module['comment']['field'],
            'sys_field' => $sysfield,
            'date_field' => 'inputtime',
            'show_field' => 'id',
            'list_field' => $this->module['comment']['comment_list_field'],
            'order_by' => 'inputtime desc',
            'where_list' => $where,
        ]);

        // 控制菜单
        if ($this->is_verify) {
            $menu = [
                '审核管理' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-edit'],
            ];
        } else {
            $menu = [
                dr_lang('%s管理', $this->cname) => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index{cid='.$this->cid.'}', 'fa fa-comments'],
                dr_lang('返回%s管理', $this->form['name']) => [APP_DIR.'/'.$this->form['table'].'/index{cid='.$this->index['cid'].'}', dr_icon($this->form['setting']['icon'])],
            ];
            if ($this->cid) {
                $menu['发布'] = [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add{cid='.$this->cid.'}', 'fa fa-plus'];
            }
            if ($this->module['comment']['review'] &&  $this->cid) {
                $menu['查看评分'] = ['show:'.APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/review_index{cid='.$this->cid.'}', 'fa fa-thumbs-o-up'];
            }
        }

        // 写入模板
        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu($menu),
            'field' => $this->init['field'],
            'index' => $this->index,
            'is_verify' => $this->is_verify,
            'comment_url' => dr_url(APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', ['cid' =>  $this->cid]),
        ]);
    }

    // ========================

    // 后台查看列表
    protected function _Admin_List() {

        list($tpl) = $this->_List(['cid' => $this->cid]);

        \Phpcmf\Service::V()->assign([
            'p' => ['cid' =>  $this->cid],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台添加内容
    protected function _Admin_Add() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        list($tpl, $data) = $this->_Post();

        \Phpcmf\Service::V()->assign([
            'data' => $data,
            'form' => dr_form_hidden(),
            'review' => $this->module['comment']['review'],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台修改内容
    protected function _Admin_Edit() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        list($tpl, $data) = $this->_Post($id);

        if (!$data) {
            $this->_admin_msg(0, dr_lang('数据不存在: '.$id));
        } elseif ($this->cid != $data['cid']) {
            $this->_admin_msg(0, dr_lang('cid不匹配'));
        } elseif ($this->is_verify && $data['status'] == 1) {
            $this->_admin_msg(0, dr_lang('已经通过了审核'));
        }

        \Phpcmf\Service::V()->assign([
            'data' => $data,
            'form' => dr_form_hidden(),
            'review' => $this->module['comment']['review'],
        ]);
        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台查看评分信息
    protected function _Admin_Review() {
        \Phpcmf\Service::V()->assign([
            'review' => $this->module['comment']['review'],
            'comment' => $this->comment_model->get_comment_index($this->cid, $this->index['catid']),
        ]);
        \Phpcmf\Service::V()->admin($this->admin_tpl_path);
        \Phpcmf\Service::V()->display('share_comment_review.html');exit;
    }

    // 后台查看内容
    protected function _Admin_Show() {

        if (!$this->cid) {
            $this->_admin_msg(0, dr_lang('缺少cid参数'));
        }

        $id = intval(\Phpcmf\Service::L('input')->get('id'));
        list($tpl, $data) = $this->_Show($id);

        if (!$data) {
            $this->_admin_msg(0, dr_lang('数据不存在: '.$id));
        } elseif ($this->cid != $data['cid']) {
            $this->_admin_msg(0, dr_lang('cid不匹配'));
        }

        \Phpcmf\Service::V()->display($tpl);
    }

    // 后台批量审核
    protected function _Admin_Status() {

        $tid = intval(\Phpcmf\Service::L('input')->get('tid'));
        $ids = \Phpcmf\Service::L('input')->get_post_ids();
        if (!$ids) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        // 格式化
        $in = [];
        foreach ($ids as $i) {
            $i && $in[] = intval($i);
        }
        if (!$in) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        $rows = \Phpcmf\Service::M()->init($this->init)->where_in('id', $in)->getAll();
        if (!$rows) {
            $this->_json(0, dr_lang('所选数据不存在'));
        }

        foreach ($rows as $row) {

            if ($row['status'] != 1) {
                if ($tid) {
                    // 拒绝
                    \Phpcmf\Service::M()->db->table($this->init['table'])->where('id', $row['id'])->update(['status' => 2]);

                    \Phpcmf\Service::M('member')->delete_admin_notice(APP_DIR.'/'.$this->form['table'].'_comment_verify/edit:cid/'.$row['cid'].'/id/'.$row['id'], SITE_ID);
                    // 提醒
                    \Phpcmf\Service::M('member')->notice($row['uid'], 3, dr_lang('模块%s表单%s：%s审核被拒绝', $this->module['name'], $this->form['name'], $this->cname));
                    // 挂钩点 被拒绝
                    \Phpcmf\Hooks::trigger('mform_comment_verify_0', $row);
                } else {
                    // 通过
                    $this->comment_model->verify_comment($row);
                }
            }
        }

        $this->_json(1, dr_lang('操作成功'));
    }

    // 后台删除内容
    protected function _Admin_Del() {
        $this->_Del(
            \Phpcmf\Service::L('input')->get_post_ids(),
            null,
            function ($rows) {
                // 对应删除提醒
                foreach ($rows as $t) {
                    \Phpcmf\Service::M('member')->delete_admin_notice(APP_DIR.'/'.$this->form['table'].'_comment_verify/edit:cid/'.$t['cid'].'/id/'.$t['id'], SITE_ID);
                    // 重新统计评论数
                    $this->comment_model->comment_update_total($t);
                    $this->comment_model->comment_update_review($t);
                }

            },
            \Phpcmf\Service::M()->dbprefix($this->init['table'])
        );
    }

    // ===========================

    /**
     * 获取内容
     * $id      内容id,新增为0
     * */
    protected function _Data($id = 0) {

        $row = $this->comment_model->table($this->comment_model->mytable.'_comment')->get($id);
        if (!$row) {
            return [];
        }

        return $row;
    }

    // 格式化保存数据 保存之前
    protected function _Format_Data($id, $data, $old) {

        // 验证父数据
        if (!$this->index) {
            $this->_json(0, dr_lang('关联内容不存在'));
        }

        // 默认数据
        $data[1]['cid'] =  $this->cid;

        // 添加评论
        if (!$id) {
            $data[1]['status'] = 1;
            $data[1]['cuid'] = $this->index['uid'];
        }

        $review = \Phpcmf\Service::L('input')->post('review');
        if ($review) {
            foreach ($review as $i => $v) {
                $data[1]['sort'.$i] = $v;
            }
        }

        return $data;
    }

    /**
     * 保存内容
     * $id      内容id,新增为0
     * $data    提交内容数组,留空为自动获取
     * $func    格式化提交的数据
     * */
    protected function _Save($id = 0, $data = [], $old = [], $func = null, $func2 = null) {

        return parent::_Save($id, $data, $old, null,
            function ($id, $data, $old) {
                // 保存之后
                if ($this->is_verify && $data[1]['status'] == 1) {
                    //审核通知
                    $this->comment_model->verify_comment($old);
                } elseif (!$old) {
                    // 后台新增
                    $this->comment_model->verify_comment($data[1]);
                } else {
                    // 修改数据
                    $this->comment_model->comment_update_total($data[1]);
                    $this->comment_model->comment_update_review($data[1]);
                }

            }
        );
    }

}
